package com.gr.staffpm.pages.projects;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.mpp.MPPReader;
import net.sf.mpxj.reader.ProjectReader;

import org.apache.shiro.SecurityUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.extensions.markup.html.tabs.TabbedPanel;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;
import org.wicketstuff.annotation.strategy.MountHybrid;

import com.gr.staffpm.StaffPMWebPage;
import com.gr.staffpm.datatypes.Project;
import com.gr.staffpm.datatypes.Task;
import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.pages.error.UnauthorizedPage;
import com.gr.staffpm.projects.service.ProjectService;
import com.gr.staffpm.security.constants.StaffPMRoles;
import com.gr.staffpm.security.service.UserService;
import com.gr.staffpm.widget.dialog.upload.AjaxUploadDialog;

/**
 * Owner, Administrator and those with read permissions can view each project
 * 
 * @author Graham Rhodes 3 May 2011 03:50:05
 */
@MountHybrid
@MountPath(path = "secure/ViewProject")
public class ViewProject extends StaffPMWebPage {

    @SpringBean(name = "projectService")
    private ProjectService projectService;
    @SpringBean(name = "userService")
    private UserService userService;
    private final Project p;
    private AjaxUploadDialog mprojectUpload;

    public ViewProject(PageParameters parameters) {
        super();
        this.p = projectService.getProject(parameters.getInt("id"));


        boolean owner = userService.getCurrentUser().equals(p.getOwner());
        boolean admin = SecurityUtils.getSubject().hasRole(StaffPMRoles.ADMIN);

        if (SecurityUtils.getSubject().isPermitted("project:read:" + p.getProjectId()) || admin || owner) {
            super.onBeforeRender();
            setDefaultModel(new Model<String>("tabPanel"));

            add(new Label("projectName", "Project: " + p.getProjectName()));
            add(new FeedbackPanel("feedback"));
            add(new AjaxLink<Void>("addFileLink") {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    launchAddFileDialog(target);
                }

            }.setVisible(false));

            add(new AjaxLink<Void>("addTaskLink") {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    launchAddTaskDialog(target);
                }

            }.setVisible(SecurityUtils.getSubject().isPermitted("project:createtasks:" + p.getProjectId()) || admin || SecurityUtils.getSubject().isPermitted("task:create")));

            List<ITab> tabs = new ArrayList<ITab>();

            tabs.add(new AbstractTab(new Model<String>("Summary")) {

                private static final long serialVersionUID = 1L;

                @Override
                public Panel getPanel(String id) {
                    return new SummaryTabPanel(id, p);
                }
            });
            tabs.add(new AbstractTab(new Model<String>("Tasks")) {

                private static final long serialVersionUID = 1L;

                @Override
                public Panel getPanel(String id) {
                    return new TasksTabPanel(id, p);
                }
            });
            if (owner || admin || SecurityUtils.getSubject().isPermitted("project:update:" + p.getProjectId())) {
                tabs.add(new AbstractTab(new Model<String>("Settings")) {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public Panel getPanel(String id) {
                        return new SettingsTabPanel(id, p);
                    }
                });
            }

            add(new TabbedPanel("tabs", tabs).add(new AttributeModifier("class", true, getDefaultModel())));
            add(mprojectUpload = new AjaxUploadDialog("mprojectUpload") {

                private static final long serialVersionUID = 1L;

                @Override
                protected void onSubmit(FileUpload upload) {
                    if (upload != null) {
                        try {
                            User curruser = userService.getCurrentUser();
                            InputStream in = upload.getInputStream();
                            ProjectReader reader = new MPPReader();
                            ProjectFile project = reader.read(in);
                            for (net.sf.mpxj.Task task : project.getAllTasks()) {
                                if (task.getID() > 0) {
                                    Date start = task.getStart();
                                    Date end = task.getFinish();
                                    Task newtask = new Task();
                                    newtask.setSummary(task.getName());
                                    newtask.setCreated(start);
                                    newtask.setDueDate(end);
                                    newtask.setCreatedBy(curruser);
                                    newtask.setLastUpdated(new Date());
                                    newtask.setDescription(task.getNotes());
                                    newtask.setAssignee(curruser);
                                    //newtask.setImportance(taskService.get)
                                    //newtask.setStatus(taskService.getOpenStatus());
                                    newtask.setResolved(false);
                                    newtask.setQueued(false);
                                    newtask.setUpdatedBy(userService.getCurrentUser());
                                }
                            }
                        } catch (Exception e) {
                            throw new IllegalStateException("Unable to write file", e);
                        }
                    }
                }
            });
        } else
            setResponsePage(UnauthorizedPage.class);
    }

    /**
     * @param target
     */
    protected void launchAddFileDialog(AjaxRequestTarget target) {
        mprojectUpload.show(target);
    }

    protected void launchAddTaskDialog(AjaxRequestTarget target) {
        setResponsePage(new AddTaskPage(p));
    }

    public Project getProject() {
        return p;
    }

    @Override
    public String getTitle() {
        return "Project: " + p.getProjectName() + " - StaffPM";
    }

}
